
import 'package:flutter01/pages/animation/hero.dart';
import 'package:flutter01/pages/animation/rive.dart';
import 'package:flutter/material.dart';



class AnimationPractice extends StatefulWidget {
  AnimationPractice({Key? key}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".


  @override
  _AnimationPracticeState createState() => _AnimationPracticeState();
}

class _AnimationPracticeState extends State<AnimationPractice>
    with SingleTickerProviderStateMixin {
// class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int _counter = 0;
  late final AnimationController _controller1;
  // late final AnimationController _controller2;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();
    _controller1 =
    AnimationController(vsync: this, duration: Duration(seconds: 1))
      ..addListener(() {
        print("${_controller1.value}");
      });
    // _controller2 = AnimationController(vsync: this,duration: Duration(seconds: 2))..addListener(() {
    //   print("${_controller2.value}");
  }

  @override
  void dispose() {
    _controller1.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("animation practice"),
      ),
      body: SingleChildScrollView(
        // color:Colors.red,
        child: Column(
          children: [
            /// rive动画
            ElevatedButton(child:Text('Rive动画->'),onPressed: (){
              Navigator.push(context,MaterialPageRoute(builder: (BuildContext context) {
                return RivePage();
              }));
            },),
            /// 隐示动画
            TweenAnimationBuilder(
                tween: Tween<Offset>(
                  // begin: 0,
                  // end: 10,
                  begin: Offset(0, 0),
                  end: Offset(100, 0),
                ),
                curve: Curves.easeInOut,
                duration: Duration(seconds: 1),
                builder: (context, value, child) {
                  return Transform.translate(
                      offset: value as Offset, child: child);
                },
                child: Container(width: 100, height: 100, color: Colors.blue)),
            AnimatedContainer(
                duration: Duration(seconds: 3, milliseconds: 1),
                width: 100,
                height: 100,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Colors.greenAccent,
                    // borderRadius: BorderRadius.circular(50),
                    gradient: LinearGradient(
                      colors: [Colors.greenAccent, Colors.orangeAccent],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      stops: [0.0, 0.5],
                    )),
                child: AnimatedSwitcher(
                  transitionBuilder: (child, animation) {
                    return FadeTransition(
                        opacity: animation,
                        child: ScaleTransition(
                          scale: animation,
                          child: child,
                        ));
                  },
                  duration: Duration(seconds: 3),
                  child: Text('nihao',
                      key: UniqueKey(), style: TextStyle(fontSize: 16)),
                )),
            Row(
                children: [Container(
                  width: 150,
                  height: 150,
                  color: Colors.blue,
                  child: AnimatedCounter(value: _counter),
                ),
                  ElevatedButton(
                    child: Text('+'),
                    onPressed:_incrementCounter,
                  ),
                ]
            ),
            SizedBox(
              height: 20,
            ),

            /// 显示动画
            Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
              ScaleTransition(
                scale: _controller1.drive(Tween(begin: 1.0, end: 2.0)),
                child: Container(
                  width: 50,
                  height: 50,
                  color: Colors.blue,
                ),
              ),
              SlideTransition(
                // position: _controller1.drive(Tween(begin:Offset(0,0),end:Offset(0,0.5))),
                position: Tween(begin: Offset(0, 0), end: Offset(0, 0.5))
                    .chain(CurveTween(curve: Curves.elasticInOut))
                    .animate(_controller1),

                child: Container(
                  width: 50,
                  height: 50,
                  color: Colors.blue,
                ),
              ),
              Column(children: [
                ElevatedButton(
                  child: Text('forward'),
                  onPressed: () {
                    _controller1.forward();
                  },
                ),
                ElevatedButton(
                  child: Text('repeat'),
                  onPressed: () {
                    _controller1.repeat();
                  },
                ),
                ElevatedButton(
                  child: Text('reverse'),
                  onPressed: () {
                    _controller1.repeat(reverse: true);
                  },
                ),
                ElevatedButton(
                  child: Text('stop'),
                  onPressed: () {
                    _controller1.stop();
                  },
                ),
                ElevatedButton(
                  child: Text('reset'),
                  onPressed: () {
                    _controller1.reset();
                  },
                ),
              ])
            ]),
            Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              SlidingBox(
                  controller: _controller1,
                  color: Colors.blue[100]!,
                  curve: Interval(0.0, 0.2)),
              SlidingBox(
                  controller: _controller1,
                  color: Colors.blue[200]!,
                  curve: Interval(0.2, 0.4)),
              SlidingBox(
                  controller: _controller1,
                  color: Colors.blue[300]!,
                  curve: Interval(0.4, 0.6)),
              SlidingBox(
                  controller: _controller1,
                  color: Colors.blue[400]!,
                  curve: Interval(0.6, 0.8)),
              SlidingBox(
                  controller: _controller1,
                  color: Colors.blue[500]!,
                  curve: Interval(0.8, 1.0)),
            ]),
            SizedBox.fromSize(size: Size(0, 10)),
            AnimatedBuilder(
              animation: _controller1,
              builder: (BuildContext context, Widget? child) {
                return Opacity(
                  opacity: _controller1.value,
                  child: Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.circular(
                              Tween<double>(begin: 0, end: 100)
                                  .evaluate(_controller1))),
                      child: Center(
                          child: FittedBox(
                              child: Text('animatedBuilder',
                                  style: TextStyle(color: Colors.white))))),
                );
              },
            ),
            SizedBox(height: 10),
            BreathLoop478(),

            /// hero 动画
            GestureDetector(
                onTap: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (BuildContext context) {
                        return HeroPage();
                      }));
                },
                child:
                Hero(tag: "flutterLogo", child: FlutterLogo(size: 50.0))),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

/// 478呼吸法
class BreathLoop478 extends StatefulWidget {
  const BreathLoop478({Key? key}) : super(key: key);

  @override
  _BreathLoop478State createState() => _BreathLoop478State();
}

class _BreathLoop478State extends State<BreathLoop478>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  bool isAnimate = false;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(vsync: this, duration: Duration(seconds: 20));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Animation animation1 = Tween(begin: 0.0, end: 1.0)
    //     .chain(CurveTween(curve: Interval(0.0, 0.2)))
    //     .animate(_controller);
    // Animation animation2 = Tween(begin: 1.0, end: 0.0)
    //     .chain(CurveTween(curve: Interval(0.4, 0.95)))
    //     .animate(_controller);

    return Column(
      children: [
        ElevatedButton(
          // onPressed: () {
          //   if (!isAnimate) {
          //     _controller.repeat(reverse: true);
          //   } else {
          //     _controller.reset();
          //   }
          //   isAnimate = !isAnimate;
          // },
            onPressed: () async {
              _controller.duration = Duration(seconds: 4);
              _controller.forward();
              await Future.delayed(Duration(seconds: 4));
              await Future.delayed(Duration(seconds: 7));

              _controller.duration = Duration(seconds: 8);
              _controller.reverse();
            },
            child: Text('478呼吸法')),
        AnimatedBuilder(
          animation: _controller,
          builder: (BuildContext context, Widget? child) {
            return Container(
              width: 300,
              height: 300,
              decoration: BoxDecoration(
                // color:Colors.blue,
                  shape: BoxShape.circle,
                  gradient: RadialGradient(
                    colors: [Colors.blue[600]!, Colors.blue[100]!],
                    // stops: _controller.value <= 0.2
                    //     ? [animation1.value, animation1.value + 0.1]
                    //     : [animation2.value, animation2.value + 0.1],
                    stops: [_controller.value, _controller.value + 0.1],
                  )),
            );
          },
        ),
      ],
    );
  }
}

class SlidingBox extends StatelessWidget {
  const SlidingBox({
    Key? key,
    required AnimationController controller,
    this.curve = const Interval(0.0, 1.0),
    this.color = Colors.blue,
  })  : _controller = controller,
        super(key: key);

  final AnimationController _controller;
  final Curve curve;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
        position: Tween(begin: Offset(0, 0), end: Offset(0.2, 0))
            .chain(CurveTween(curve: curve))
            .animate(_controller),
        child: Container(width: 300, height: 100, color: color));
  }
}

class AnimatedCounter extends StatelessWidget {
  final int value;
  final Duration duration;
  AnimatedCounter({this.value = 0, this.duration = const Duration(seconds: 1)});

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder(
      tween: Tween<double>(end: value.toDouble()),
      duration: duration,
      builder: (context, double value, child) {
        final whole = value ~/ 1;
        final decimal = value - whole;
        // print('$whole-$decimal');
        return Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
                top: -100 * decimal,
                child: Opacity(
                  opacity: 1.0 - decimal,
                  child: Text('$whole',
                      style: TextStyle(
                        fontSize: 100,
                      )),
                )),
            Positioned(
                top: 100 - decimal * 100,
                child: Opacity(
                  opacity: decimal,
                  child: Text('${whole + 1}',
                      style: TextStyle(
                        fontSize: 100,
                      )),
                ))
          ],
        );
      },
    );
  }
}
